package pdf;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfMargins;

public class Combo {
	@SuppressWarnings("resource")
	public static int SplitPDF(String filePath,String userinput){
		
		String outputFile = filePath+"\\"+userinput+"\\"+userinput+"DO-wATME.pdf";
		FileInputStream streamx = null;
		
		try {
			streamx = new FileInputStream(new File(filePath+"\\"+userinput+"\\"+userinput+"ATME.pdf"));
			streamx.close();
		} catch (IOException e) {
			return 2;
		}
	
		//Divide ATME
		SplitPDF2(filePath,userinput);
			
        FileInputStream stream1 = null;
		try {
			stream1 = new FileInputStream(new File(filePath+"\\"+userinput+"\\"+userinput+"DO.pdf"));
		} catch (FileNotFoundException e) {
			return 1;
		}
       
        FileInputStream stream3 = null;
		try {
			stream3 = new FileInputStream(new File(filePath+"\\"+userinput+"\\"+userinput+".3461.pdf"));
		} catch (FileNotFoundException e) {
			return 3;
		}

		
		FileInputStream stream2 = null;
		try {
			stream2 = new FileInputStream(new File(filePath+"\\"+userinput+"\\"+userinput+"ATME.pdf"));
		} catch (FileNotFoundException e) {
			return 2;
		}
        // Load pdf
        InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};
        
        // Combine Pdf Files
        PdfDocumentBase doc = PdfDocument.mergeFiles(streams);
        
        //Save pdf file 
        doc.save(outputFile);
        try {
			stream1.close();
			stream2.close();
	        stream3.close();
	        streamx.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        doc.close();
        return 0;
	}
	
	public static void SplitPDF2(String filePath,String userinput) {
		 PdfDocument doc = new PdfDocument();
	     doc.loadFromFile(filePath+"\\"+userinput+"\\"+userinput+"ATME.pdf");
	     PdfDocument newpdf1 = new PdfDocument();
	     PdfPageBase page;  
	     page = newpdf1.getPages().add(doc.getPages().get(0).getSize(), new PdfMargins(0));
	     doc.getPages().get(0).createTemplate().draw(page, new Point2D.Float(0,0));
	     newpdf1.saveToFile(filePath+"\\"+userinput+"\\"+userinput+"ATME.pdf");
	     doc.close();
	}
}
